package com.tx.studentManager.realm;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.tx.studentManager.model.Role;
import com.tx.studentManager.model.User;
import com.tx.studentManager.service.UserService;

//@Service("monitorRealm")
public class MonitorRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	public MonitorRealm() {
		super();
	}

	// 授权方法,授权查询时回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		if (principals == null) {
			throw new AuthorizationException("Principals 对象不能为空");
		}
		// 两种获取用户名方法
		// String
		// userName=(String)principals.fromRealm(getName()).iterator().next();
		String currentUsername = (String) super.getAvailablePrincipal(principals);
		User user = null;

		List<User> users = userService.findBy("userName", currentUsername);
		if (users == null || users.size() <= 0) {
			return null;
		} else {
			user = users.get(0);
		}

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		Set<String> roleSet = new LinkedHashSet<String>(); // 角色集合
		Set<String> authoritySet = new LinkedHashSet<String>(); // 权限集合

		if (null != user && 0 != user.getActivated()) { // 判断是否用户是否禁用
			Role role = user.getRole();
			roleSet.add(role.getRoleName());
		}
		info.setRoles(roleSet); // 设置角色
		info.setStringPermissions(authoritySet); // 设置权限

		return info;
	}

	// 认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthorizationException{
		/* 这里编写认证代码 */
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		User user = userService.getUserByUserName(userName);
		
		if (user != null) {
			if (user.getActivated()==0) {
				throw new LockedAccountException();
			}
			if (user.getPassword().equals(new String(token.getPassword()))) {
				return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
			} else {
				// 密码错误
				throw new IncorrectCredentialsException(" Password for user " + userName);
			}

		} else {
			// 用户不存在
			throw new UnknownAccountException("用户" + userName + "不存在");
		}
	}

	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	} 
	
	/** 
     * 清除所有用户授权信息缓存. 
     */  
	 public void clearAllCachedAuthorizationInfo() {  
	        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();  
	        if (cache != null) {  
	            for (Object key : cache.keys()) {  
	                cache.remove(key);  
	            }  
	        }  
	    }  

}
